
// 初始化用户信息
document.addEventListener('DOMContentLoaded', async () => {
    try {
        const res = await fetch('/user/getUserInfo', {
            method: 'POST'
        });
        const data = await res.json();
        if (data.code === 200) {
            window.userInfo = data.data;
            updateUserInfo(data.data);
        }
    } catch (error) {
        console.error('获取用户信息失败:', error);
    }
});

// 更新用户信息显示
function updateUserInfo(user) {
    document.querySelector('.user-avatar').src = user.avatar || '/images/banners/1.png';
    document.querySelector('.username').textContent = user.userName;
}

// 用户菜单控制
let menuTimeout;
function showUserMenu() {
    clearTimeout(menuTimeout);
    document.querySelector('.user-menu').classList.add('active');
}

function hideUserMenu() {
    menuTimeout = setTimeout(() => {
        document.querySelector('.user-menu').classList.remove('active');
    }, 200);
}

// 退出登录
function logout() {
    localStorage.removeItem('cart');
    window.location.href = '/user/loginPage';
}

// 显示订单抽屉
async function showOrderDrawer() {
    document.querySelector('.order-drawer').classList.add('active');
    document.getElementById('orderOverlay').classList.add('active');

    try {
        const data = await fetchData(API.getMyOrderList);
        renderOrders(data.data);
    } catch (error) {
        console.error('获取订单失败:', error);
    }
}


// 关闭订单抽屉
function closeOrderDrawer() {
    document.querySelector('.order-drawer').classList.remove('active');
    document.getElementById('orderOverlay').classList.remove('active');
}

// 渲染订单列表
function renderOrders(orders) {
    const container = document.querySelector('.order-list');
    container.innerHTML = orders.map(order => `
        <div class="order-item">
            <div class="order-image">
                <img src="${order.imgUrl || '/images/default-product.jpg'}">
            </div>
            <div class="order-detail">
                <div class="order-title">${order.title}</div>
                <div>数量：${order.quantity}</div>
                <div>金额：¥ ${order.amount.toFixed(2)}</div>
                <div class="order-time">${new Date(order.createTime).toLocaleString()}</div>
            </div>
        </div>
    `).join('');
}

function showResetPwdModal() {
    const modal = document.createElement('div');
    modal.className = 'reset-modal';
    modal.innerHTML = `
        <div class="modal-content">
            <span class="close-btn" onclick="this.parentElement.parentElement.remove()">&times;</span>
            <h3>重置密码</h3>
            <form onsubmit="handleResetPwd(event)">
                <div class="form-group">
                    <input type="password" id="oldPwd" placeholder="原密码" required>
                </div>
                <div class="form-group">
                    <input type="password" id="newPwd" placeholder="新密码（至少6位）" required minlength="6">
                </div>
                <button type="submit" class="submit-btn">提交</button>
            </form>
        </div>
    `;
    document.body.appendChild(modal);
}

// 修改后的 handleResetPwd
async function handleResetPwd(event) {
    event.preventDefault(); // 阻止表单默认提交行为

    const oldPwd = document.getElementById('oldPwd').value;
    const newPwd = document.getElementById('newPwd').value;

    if (newPwd.length < 6) {
        alert('新密码至少需要6位');
        return;
    }

    try {
        const res = await fetch('/user/resetPwd', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({ oldPassword: oldPwd, newPassword: newPwd })
        });
        const data = await res.json();
        if (data.code === 200) {
            alert('密码修改成功，请重新登录');
            logout();
        } else {
            alert('修改失败：' + data.msg);
        }
    } catch (error) {
        alert('网络错误，请稍后重试');
    }
}


async function fetchData(url, params = {}) {
    const response = await fetch(url, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'X-Requested-With': 'XMLHttpRequest'
        },
        body: JSON.stringify(params)
    });
    if (!response.ok) throw new Error('请求失败');
    return response.json();
}